package cumeo89.chii.client.util;

import com.google.gwt.core.client.JavaScriptObject;

public final class JSStringArray extends JavaScriptObject {

	protected JSStringArray() {
	}

	public native int length() /*-{ return this.length; }-*/;

	public native String get(int i) /*-{ return this[i]; }-*/;

	public native void set(int i, String e) /*-{ this[i] = e; }-*/;

	public native String join() /*-{ return this.join(); }-*/;

	public native String join(String sep) /*-{ return this.join(sep); }-*/;

	public int binarySearch(String s) {
		return binarySearch(s, false);
	}

	public int binarySearch(String s, boolean caseInsensitive) {
		return doBinarySearch(s, 0, length() - 1, caseInsensitive);
	}

	public int binarySearch(String s, int fromIndex, int toIndex) {
		return binarySearch(s, fromIndex, toIndex, false);
	}

	public int binarySearch(String s, int fromIndex, int toIndex,
			boolean caseInsensitive) {
		rangeCheck(length(), fromIndex, toIndex);
		return doBinarySearch(s, fromIndex, toIndex, caseInsensitive);
	}

	private native int doBinarySearch(String s, int low, int high,
			boolean case_insensitive) /*-{
		s = (case_insensitive) ? s.toLowerCase() : s;
		while (low <= high) {
			mid = parseInt((low + high) / 2)
			val = (case_insensitive) ? this[mid].toLowerCase() : this[mid];
			if (val > s) {
				high = mid - 1;
			} else if (val < s) {
				low = mid + 1;
			} else {
				return mid;
			}
		}
		return -(mid + 1);
	}-*/;

	public native void sort() /*-{ this.sort();	}-*/;

	private static void rangeCheck(int arrayLen, int fromIndex, int toIndex) {
		if (fromIndex > toIndex)
			throw new IllegalArgumentException("fromIndex(" + fromIndex
					+ ") > toIndex(" + toIndex + ")");
		if (fromIndex < 0)
			throw new ArrayIndexOutOfBoundsException(fromIndex);
		if (toIndex > arrayLen)
			throw new ArrayIndexOutOfBoundsException(toIndex);
	}

}